# coding=utf-8
from flask import Flask, jsonify, render_template, request
from py2neo import Graph
import jw.Q_Search as search
import json
import logging


logging.basicConfig(level=logging.WARNING,
                format='%(asctime)s %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='logs/pro2.log',
                filemode='a')

app = Flask(__name__)
graph = Graph(
    "http://localhost:7474",
    username="neo4j",
    password="456852"
)

# f = open("recommend_list.json","r")
# d = json.loads(f.read())
# f.close()
def buildNodes_a(nodeRecord):
    data = {"id": str(nodeRecord['a']['id']), "name": str(nodeRecord['a']['name']),"label":"A"}

    return {"data": data}


def buildNodes_b(nodeRecord):
    data = {"id": str(nodeRecord['b']['id']), "name": str(nodeRecord['b']['name']), "label":"B"}

    return {"data": data}


def buildNodes_c(nodeRecord):
    data = {"id": str(nodeRecord['c']['id']),
            "name": str(nodeRecord['c']['name']),
            "label":"C"}

    return {"data": data}


def buildNodes_d(nodeRecord):
    data = {"id": str(nodeRecord['d']['id']), "name": str(nodeRecord['d']['name']), "label":"D"}

    return {"data": data}


def buildNodes_s(nodeRecord):
    data = {"id": str(nodeRecord['s']['id']), "name": str(nodeRecord['s']['name']), "label":"S"}

    return {"data": data}


def buildNodes_T(nodeRecord):
    data = {"id": str(nodeRecord['t']['id']), "name": str(nodeRecord['t']['name']), "label":"T"}

    return {"data": data}

def buildEdges(relationRecord):
    data = {"source": str(relationRecord['s']['id']),
            "target": str(relationRecord['t']['id']),
            "relationship": relationRecord['r']}

    return {"data": data}



def get_recommendation(entities):

    try:
        q = list(entities.values())[1][0]
        print(q)
        cypher = """match(s:D)-[r:relate_to]->(t:D) where s.name='{}' return t""".format(q)
        temp = graph.run(cypher).data()
        recommend = ''
        for i in temp:
            recommend += i['t']['name']
        return recommend
    except:
        return "未检测到相关疾病"
        
@app.route('/')
def hello_world():
    logging.warning("====== user ip: {} ======".format(request.remote_addr))
    return render_template('index000.html')

@app.route('/search', methods=['GET'])
def index1():
    return render_template('index1.html')

@app.route('/search', methods=['POST'])
def index2():
    query = request.form['Search']
    logging.warning("====== Query: {} ======".format(query))
    #query = query.replace("\n","")
    global entities
    global qtype
    entities,answer,qtype = search.get_query_type(query)

    question = str(query).replace('\n','')
    recommendation = get_recommendation(entities)
    answer = str(answer)
    content = {'question':question,
               'recommend':recommendation,
               'answer':answer,
               }


    return render_template('index2.html',**content)

@app.route('/graph')
def get_graph():
    nodes = []
    edges = []
    if qtype == 0:
        for i in entities[1]:
            nodes += list(map(buildNodes_d, graph.run('''match(d:D)-[r:located_at]->(b:B) where d.name='{}' return d'''.format(i))))
            nodes += list(map(buildNodes_b, graph.run('''match(d:D)-[r:located_at]->(b:B) where d.name='{}' return b'''.format(i))))
            edges += list(map(buildEdges, graph.run('''match(s:D)-[r:located_at]->(t:B) where s.name='{}' return r,s,t'''.format(i))))
    elif qtype == 1:
        for i in entities[2]:
            nodes += list(map(buildNodes_s, graph.run('''match(d:D)-[r:has_symptom]->(s:S) where s.name='{}' return s'''.format(i))))
            nodes += list(map(buildNodes_d, graph.run('''match(d:D)-[r:has_symptom]->(s:S) where s.name='{}' return d'''.format(i))))
            edges += list(map(buildEdges, graph.run('''match(s:D)-[r:has_symptom]->(t:S) where t.name='{}' return r,s,t'''.format(i))))
    elif qtype == 2:
        for i in entities[2]:
            nodes += list(map(buildNodes_s, graph.run('''match(d:D)-[r:has_symptom]->(s:S) where s.name='{}' return s'''.format(i))))
            nodes += list(map(buildNodes_d, graph.run('''match(d:D)-[r:has_symptom]->(s:S) where s.name='{}' return d'''.format(i))))
            edges += list(map(buildEdges, graph.run('''match(s:D)-[r:has_symptom]->(t:S) where t.name='{}' return r,s,t'''.format(i))))
            for j in list(map(buildNodes_d, graph.run('''match(d:D)-[r:has_symptom]->(s:S) where s.name='{}' return d'''.format(i)))):
                nodes += list(map(buildNodes_c, graph.run('''match(d:D)-[r:need_check]->(c:C) where d.name='{}' return c'''.format(j['data']['name']))))
                edges += list(map(buildEdges, graph.run('''match(s:D)-[r:need_check]->(t:C) where s.name='{}' return r,s,t'''.format(j['data']['name']))))
    elif qtype == 3:
        for i in entities[0]:
            nodes += list(map(buildNodes_b, graph.run('''match(d:D)-[r:located_at]->(b:B) where b.name='{}' return b'''.format(i))))
            nodes += list(map(buildNodes_d, graph.run('''match(d:D)-[r:located_at]->(b:B) where b.name='{}' return d'''.format(i))))
            edges += list(map(buildEdges, graph.run('''match(s:D)-[r:located_at]->(t:B) where t.name='{}' return r,s,t'''.format(i))))






    return jsonify(elements = {"nodes": nodes, "edges":edges})
if __name__ == '__main__':
    app.run(debug = True)